<template>
  <div class="space-y-4">
    <!-- 拖拽上传区域 -->
    <div
      v-if="imagePreviews.length === 0"
      @drop.prevent="handleDrop"
      @dragover.prevent="isDragging = true"
      @dragleave.prevent="isDragging = false"
      class="border-2 border-dashed rounded-lg p-8 text-center transition-all cursor-pointer"
      :class="
        isDragging
          ? 'border-blue-500 bg-blue-50'
          : 'border-gray-300 hover:border-blue-400 hover:bg-gray-50'
      "
      @click="triggerFileInput"
    >
      <input
        ref="fileInput"
        type="file"
        accept="image/jpeg,image/png,image/jpg"
        multiple
        class="hidden"
        @change="handleFileSelect"
      />

      <Upload class="w-12 h-12 mx-auto text-gray-400 mb-4" />
      <p class="text-lg font-medium text-gray-700 mb-2">
        点击上传或拖拽图片到此处
      </p>
      <p class="text-sm text-gray-500 mb-4">
        支持 JPEG、PNG 格式，单个文件不超过 10MB<br />
        <span class="text-blue-500 font-medium">支持多张图片同时上传</span>
      </p>
      <button
        type="button"
        class="px-6 py-2 bg-blue-500 hover:bg-blue-600 text-white font-medium rounded-lg transition-colors"
      >
        选择图片
      </button>
    </div>

    <!-- 多图片预览和OCR状态 -->
    <div v-else class="space-y-4">
      <!-- 图片网格预览 -->
      <div class="bg-white rounded-lg border border-gray-200 p-4">
        <div class="flex items-center justify-between mb-3">
          <h4 class="font-medium text-gray-800">
            已上传 {{ imagePreviews.length }} 张图片
          </h4>
          <button
            type="button"
            @click="addMoreImages"
            class="text-blue-500 hover:text-blue-600 text-sm font-medium"
          >
            + 添加更多
          </button>
        </div>
        
        <div class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3">
          <div
            v-for="(preview, index) in imagePreviews"
            :key="index"
            class="relative group rounded-lg overflow-hidden border border-gray-200"
          >
            <img
              :src="preview.url"
              :alt="`图片 ${index + 1}`"
              class="w-full h-32 object-cover"
            />
            
            <!-- 删除按钮 -->
            <button
              type="button"
              @click="removeImage(index)"
              class="absolute top-1 right-1 p-1 bg-red-500 hover:bg-red-600 text-white rounded-full opacity-0 group-hover:opacity-100 transition-opacity"
            >
              <X class="w-4 h-4" />
            </button>
            
            <!-- 识别状态 -->
            <div
              v-if="isProcessing && preview.processing"
              class="absolute inset-0 bg-black bg-opacity-50 flex items-center justify-center"
            >
              <Loader class="w-6 h-6 text-white animate-spin" />
            </div>
            
            <!-- 识别成功标记 -->
            <div
              v-if="preview.completed"
              class="absolute top-1 left-1 p-1 bg-green-500 rounded-full"
            >
              <CheckCircle class="w-4 h-4 text-white" />
            </div>
          </div>
        </div>
      </div>

      <!-- OCR处理进度 -->
      <div v-if="isProcessing" class="bg-blue-50 border border-blue-200 rounded-lg p-4">
        <div class="flex items-center justify-between mb-2">
          <div class="flex items-center">
            <Loader class="w-5 h-5 text-blue-500 animate-spin mr-2" />
            <span class="font-medium text-gray-800">正在识别文字...</span>
          </div>
          <span class="text-sm text-gray-600">{{ ocrProgress }}%</span>
        </div>
        <div class="w-full bg-gray-200 rounded-full h-2">
          <div
            class="bg-blue-500 h-2 rounded-full transition-all"
            :style="{ width: `${ocrProgress}%` }"
          ></div>
        </div>
        <p class="text-xs text-gray-600 mt-2">
          已完成 {{ completedCount }}/{{ imagePreviews.length }} 张
        </p>
      </div>

      <!-- OCR识别的文本 -->
      <div v-if="ocrText && !isProcessing" class="bg-gradient-to-br from-blue-50 to-indigo-50 border-2 border-blue-300 rounded-lg overflow-hidden">
        <div class="bg-blue-500 text-white px-4 py-2 flex items-center justify-between">
          <h4 class="font-medium flex items-center">
            <CheckCircle class="w-5 h-5 mr-2" />
            识别成功 ({{ ocrText.length }} 个字符)
          </h4>
          <button
            type="button"
            @click="copyToClipboard"
            class="text-white hover:text-blue-100 text-sm font-medium px-3 py-1 rounded hover:bg-blue-600 transition-colors"
          >
            复制文本
          </button>
        </div>
        <div class="p-4">
          <div class="bg-white rounded-lg p-4 mb-3 max-h-60 overflow-y-auto">
            <p class="text-sm text-gray-800 whitespace-pre-wrap leading-relaxed">{{ ocrText }}</p>
          </div>
          <p class="text-xs text-gray-600 mb-3">
            <AlertCircle class="w-3 h-3 inline mr-1" />
            已合并 {{ imagePreviews.length }} 张图片的识别结果，请仔细核对
          </p>
          <div class="flex space-x-2">
            <button
              type="button"
              @click="useOCRText"
              class="flex-1 px-4 py-2 bg-blue-500 hover:bg-blue-600 text-white font-medium rounded-lg transition-colors flex items-center justify-center"
            >
              <FileText class="w-4 h-4 mr-2" />
              使用此文本
            </button>
            <button
              type="button"
              @click="startOCR"
              class="px-4 py-2 bg-gray-100 hover:bg-gray-200 text-gray-700 font-medium rounded-lg transition-colors flex items-center"
              title="重新识别"
            >
              <Scan class="w-4 h-4 mr-2" />
              重新识别
            </button>
            <button
              type="button"
              @click="clearAllImages"
              class="px-4 py-2 bg-gray-100 hover:bg-gray-200 text-gray-700 font-medium rounded-lg transition-colors flex items-center"
            >
              <Trash2 class="w-4 h-4 mr-2" />
              清空重传
            </button>
          </div>
        </div>
      </div>

      <!-- 操作按钮（未识别时） -->
      <div v-if="!isProcessing && !ocrText" class="flex space-x-2">
        <button
          type="button"
          @click="startOCR"
          class="flex-1 px-4 py-2 bg-blue-500 hover:bg-blue-600 text-white font-medium rounded-lg transition-colors flex items-center justify-center"
        >
          <Scan class="w-4 h-4 mr-2" />
          开始批量识别
        </button>
        <button
          type="button"
          @click="clearAllImages"
          class="px-4 py-2 bg-gray-100 hover:bg-gray-200 text-gray-700 font-medium rounded-lg transition-colors flex items-center"
        >
          <Trash2 class="w-4 h-4 mr-2" />
          清空
        </button>
      </div>

      <!-- 错误提示 -->
      <div v-if="error" class="p-4 bg-red-50 border border-red-200 rounded-lg">
        <div class="flex items-start">
          <AlertCircle class="w-5 h-5 text-red-400 flex-shrink-0 mt-0.5" />
          <p class="ml-3 text-sm text-red-700">{{ error }}</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { Upload, Loader, CheckCircle, Scan, Trash2, FileText, AlertCircle, X } from 'lucide-vue-next';
import { uploadAndRecognize, uploadAndRecognizeMultiple } from '@/services/uploadApi.js';

const emit = defineEmits(['ocr-complete', 'ocr-error']);

// 状态
const fileInput = ref(null);
const isDragging = ref(false);
const imagePreviews = ref([]); // [{url, file, processing, completed}]
const imageFiles = ref([]);
const isProcessing = ref(false);
const ocrProgress = ref(0);
const completedCount = ref(0);
const ocrText = ref('');
const error = ref('');

// 文件大小限制 (10MB)
const MAX_FILE_SIZE = 10 * 1024 * 1024;

/**
 * 触发文件选择
 */
const triggerFileInput = () => {
  fileInput.value?.click();
};

/**
 * 添加更多图片
 */
const addMoreImages = () => {
  fileInput.value?.click();
};

/**
 * 处理拖拽放置
 */
const handleDrop = (e) => {
  isDragging.value = false;
  const files = Array.from(e.dataTransfer.files);
  
  if (files.length > 0) {
    handleFiles(files);
  }
};

/**
 * 处理文件选择
 */
const handleFileSelect = (e) => {
  const files = Array.from(e.target.files);
  
  if (files.length > 0) {
    handleFiles(files);
  }
  
  // 清空input以便可以重复选择相同文件
  e.target.value = '';
};

/**
 * 处理多个文件
 */
const handleFiles = (files) => {
  error.value = '';
  
  files.forEach((file) => {
    // 验证文件类型
    if (!['image/jpeg', 'image/png', 'image/jpg'].includes(file.type)) {
      error.value = `文件 ${file.name} 格式不支持，只支持 JPEG 和 PNG 格式`;
      return;
    }
    
    // 验证文件大小
    if (file.size > MAX_FILE_SIZE) {
      error.value = `文件 ${file.name} 大小超过 10MB`;
      return;
    }
    
    // 创建预览
    const reader = new FileReader();
    reader.onload = (e) => {
      imagePreviews.value.push({
        url: e.target.result,
        file: file,
        processing: false,
        completed: false,
      });
      imageFiles.value.push(file);
    };
    reader.readAsDataURL(file);
  });
  
  // 如果是首次上传，自动开始OCR
  if (imagePreviews.value.length === 0) {
    setTimeout(() => {
      if (imageFiles.value.length > 0) {
        startOCR();
      }
    }, 500);
  }
};

/**
 * 删除单张图片
 */
const removeImage = (index) => {
  imagePreviews.value.splice(index, 1);
  imageFiles.value.splice(index, 1);
  
  // 如果删光了，清空OCR结果
  if (imagePreviews.value.length === 0) {
    ocrText.value = '';
    error.value = '';
  }
};

/**
 * 清空所有图片
 */
const clearAllImages = () => {
  imagePreviews.value = [];
  imageFiles.value = [];
  ocrText.value = '';
  error.value = '';
  ocrProgress.value = 0;
  completedCount.value = 0;
  
  if (fileInput.value) {
    fileInput.value.value = '';
  }
};

/**
 * 开始批量OCR识别
 */
const startOCR = async () => {
  if (imageFiles.value.length === 0) {
    error.value = '请先选择图片';
    return;
  }

  isProcessing.value = true;
  ocrProgress.value = 0;
  completedCount.value = 0;
  error.value = '';
  ocrText.value = '';
  
  // 标记所有图片为处理中
  imagePreviews.value.forEach(preview => {
    preview.processing = true;
    preview.completed = false;
  });
  
  try {
    console.log(`[ImageUpload] Starting batch OCR for ${imageFiles.value.length} images...`);
    
    // 模拟进度更新
    const progressInterval = setInterval(() => {
      if (ocrProgress.value < 90) {
        ocrProgress.value += 5;
      }
    }, 300);
    
    // 调用批量OCR API
    const result = await uploadAndRecognizeMultiple(imageFiles.value);
    
    clearInterval(progressInterval);
    ocrProgress.value = 100;
    completedCount.value = imageFiles.value.length;
    
    console.log('[ImageUpload] Batch OCR API response:', result);
    console.log('[ImageUpload] result.success:', result.success);
    console.log('[ImageUpload] result.data:', result.data);
    console.log('[ImageUpload] result.results:', result.results);
    
    // 提取识别的文本
    // 兼容两种数据格式：
    // 1. { success: true, data: { results: [...] } } - 标准格式
    // 2. { total: X, results: [...] } - 直接格式
    const resultsData = (result.success && result.data && result.data.results) 
      ? result.data 
      : (result.results ? result : null);
    
    if (resultsData && resultsData.results) {
      // 合并所有识别结果
      const allTexts = resultsData.results
        .map((r, index) => {
          // 标记图片为已完成
          if (imagePreviews.value[index]) {
            imagePreviews.value[index].completed = true;
            imagePreviews.value[index].processing = false;
          }
          
          // 后端返回格式: { success: true, data: { text, confidence } }
          if (r.success && r.data && r.data.text) {
            return r.data.text;
          }
          return null;
        })
        .filter(text => text) // 过滤空文本和失败的识别
        .join('\n\n'); // 用两个换行分隔不同图片的内容
      
      ocrText.value = allTexts;
      
      // 计算平均置信度（仅统计成功的）
      const successResults = resultsData.results.filter(r => r.success && r.data);
      const avgConfidence = successResults.length > 0 
        ? successResults.reduce((sum, r) => sum + (r.data.confidence || 0), 0) / successResults.length 
        : 0;
      console.log(`[ImageUpload] Batch OCR completed: ${resultsData.successful}/${resultsData.total} successful, avg confidence: ${(avgConfidence * 100).toFixed(1)}%`);
      
      // 如果有失败的，给用户提示
      if (resultsData.failed > 0) {
        error.value = `部分图片识别失败（${resultsData.failed}/${resultsData.total}），请检查图片质量`;
      } else if (avgConfidence < 0.7 && avgConfidence > 0) {
        error.value = `识别完成，但平均置信度较低（${(avgConfidence * 100).toFixed(0)}%），请仔细校对文字`;
      }
      
      // 通知父组件
      emit('ocr-complete', ocrText.value);
      
      console.log('[ImageUpload] Batch OCR completed successfully');
    } else {
      throw new Error('OCR返回数据格式错误');
    }
    
  } catch (err) {
    console.error('[ImageUpload] Batch OCR failed:', err);
    
    // 根据错误类型提供友好提示
    let errorMessage = 'OCR识别失败，请重试或手动输入';
    
    if (err.code === 'ECONNABORTED' || err.message?.includes('timeout')) {
      errorMessage = 'OCR识别超时，请检查图片数量或网络连接';
    } else if (err.status === 401) {
      errorMessage = '未登录或登录已过期，请重新登录';
    } else if (err.status === 400) {
      errorMessage = err.message || '图片格式不正确或文件过大';
    } else if (err.message) {
      errorMessage = err.message;
    }
    
    error.value = errorMessage;
    emit('ocr-error', err);
  } finally {
    isProcessing.value = false;
    // 清除处理中状态
    imagePreviews.value.forEach(preview => {
      preview.processing = false;
    });
  }
};

/**
 * 使用OCR识别的文本
 */
const useOCRText = () => {
  if (ocrText.value) {
    emit('ocr-complete', ocrText.value);
    console.log('[ImageUpload] OCR text confirmed and sent to parent');
  }
};

/**
 * 复制文本到剪贴板
 */
const copyToClipboard = async () => {
  try {
    await navigator.clipboard.writeText(ocrText.value);
    console.log('[ImageUpload] Text copied to clipboard');
    // TODO: 显示一个临时的"已复制"提示
  } catch (err) {
    console.error('[ImageUpload] Failed to copy text:', err);
    error.value = '复制失败，请手动复制';
  }
};

// 暴露方法供父组件调用
defineExpose({
  clearAllImages,
});
</script>
